/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.serviceapp.service.members.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.BatchCardRecord;
import com.qinyeit.serviceapp.entity.DeliveryDetail;
import com.qinyeit.serviceapp.entity.MemberCard;
import com.qinyeit.serviceapp.entity.enums.DeliveryState;
import com.qinyeit.serviceapp.entity.enums.PeriodType;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.repository.members.DeliveryDetailRepository;
import com.qinyeit.serviceapp.service.members.BatchCardRecordService;
import com.qinyeit.serviceapp.service.members.MemberCardService;
import com.qinyeit.serviceapp.utils.CompuUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.repository.jdbc.PageNamedParameterJdbcTemplate;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.qinyetech.springstage.core.service.BaseService;
import com.qinyeit.serviceapp.entity.DeliveryRecord;
import com.qinyeit.serviceapp.repository.members.DeliveryRecordRepository;
import com.qinyeit.serviceapp.service.members.DeliveryRecordService;

import java.util.List;
import java.util.Map;

/** 
 * ClassName: DeliveryRecordServiceImpl <br/> 
 * Function: 配送记录 业务实现 <br/> 
 * date: 2018-12-04 11:14:55 <br/> 
 * 
 * @author liuwenjin
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@Transactional
public class DeliveryRecordServiceImpl extends BaseService<DeliveryRecord, Long> implements DeliveryRecordService {


	@Autowired
	private DeliveryRecordRepository deliveryRecordRepository;
	@Autowired
	private PageNamedParameterJdbcTemplate jdbcTemplate;
	@Autowired
	private MemberCardService memberCardService;
	@Autowired
	private DeliveryDetailRepository deliveryDetailRepository;
	@Autowired
	private BatchCardRecordService batchCardRecordService;


	@Override
	public void saveDetail(DeliveryRecord record) {
		//配送明细 会员卡
		String sql = "SELECT * from member_cards where batch_id = :batchId and branch_id is null ORDER BY no asc LIMIT 0,:count";
		QyMap map = QyMap.map("batchId",record.getBatch().getId()).setv("count",record.getCount());
		List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql,map);

		log.info("---maop :  {}",mapList);


		DeliveryDetail detail = null;
		MemberCard memberCard = null;
		QyMap en = null;
		List<Long> ids = Lists.newArrayList();
		List<DeliveryDetail> detailList = Lists.newArrayList();
		if(CollectionUtils.isNotEmpty(mapList)){
			for (Map<String, Object> item : mapList) {
				en = QyMap.WRAP(item);
				detail = new DeliveryDetail();
//				memberCard = memberCardService.findById(en.getLong("id"));
				detail.setCardId(en.getLong("id"));
				detail.setDeliveryId(record.getId());
				detail.setState(DeliveryState.DELIVERY);
				detail.setMerchantGroupId(record.getMerchantGroupId());
				detailList.add(detail);
				ids.add(en.getLong("id"));
			}
		}
		deliveryDetailRepository.saveAll(detailList);

		//更新会员卡 将会员卡门店id 保存
		sql = "update member_cards set branch_id = :branchId where id in(:ids)";
		map = QyMap.NEW().setv("branchId",record.getBranchId()).setv("ids",ids);
		jdbcTemplate.update(sql,map);

		//修改制卡记录中配送数量
		BatchCardRecord cardRecord = record.getBatch();
		cardRecord.setDeliverCount(cardRecord.getDeliverCount()+ids.size());
		batchCardRecordService.update(cardRecord);
	}

	@Override
	public Long getBindVips(Long deliveryId) {

		String sql = "SELECT COUNT(*)\n" +
				"FROM delivery_details d\n" +
				"\tLEFT JOIN member_cards c ON c.id = d.card_id\n" +
				"WHERE vip_id IS NOT NULL\n" +
				"\tAND delivery_id = :deliveryId";
		QyMap map = QyMap.map("deliveryId",deliveryId);
		Long count = jdbcTemplate.queryForScalar(sql,map,Long.class);
		return count;
	}

	@Override
	public Page<Map<String,Object>> showDetails(Long deliveryId,Searchable searchable) {
		String sql = "SELECT d.state,c.no as card_no,c.id as card_id,c.type_id,c.deposit,\n" +
				"\tr.batch_id,b.period,t.name as type_name,r.id as delivery_id\n" +
				" from delivery_details d\n" +
				"LEFT JOIN member_cards c on c.id = d.card_id\n" +
				"LEFT JOIN delivery_records r on r.id = d.delivery_id\n" +
				"LEFT JOIN batch_card_records b on b.id = r.batch_id\n" +
				"LEFT JOIN member_card_types t on t.id = c.type_id" +
				" where r.id = :deliveryId";
		QyMap map = QyMap.map("deliveryId",deliveryId);
		Page<Map<String,Object>> list = jdbcTemplate.queryForList(sql,map,searchable.getPage());
		if(CollectionUtils.isNotEmpty(list.getContent())){
			for (Map<String, Object> objectMap : list.getContent()) {
				objectMap.put("periodText", PeriodType.valueOf(objectMap.get("period").toString()).getText());
				objectMap.put("stateText", DeliveryState.valueOf(objectMap.get("state").toString()).getText());
			}
		}
		return list;
	}

	@Override
	public void deleteData(Long deliveryRecordId) {

		//配送记录
		String sql = "SELECT * from delivery_records where id = :deliveryRecordId";
		QyMap map = QyMap.map("deliveryRecordId",deliveryRecordId);
		Map<String,Object> recordMap = jdbcTemplate.queryForMap(sql,map);
//		1.更新批量制卡中的已配送数量
		sql = "update batch_card_records set deliver_count = deliver_count-:count where id = :batchId";
		QyMap bmap = QyMap.map("count",recordMap.get("count")).setv("batchId",recordMap.get("batch_id"));
		jdbcTemplate.update(sql,bmap);

//		2.将配送明细对应的会员卡的门店ID置为NULL
		sql = "update member_cards set branch_id = null where id in(  SELECT card_id from delivery_details where delivery_id = :deliveryRecordId )";
		jdbcTemplate.update(sql,map);

//		3.物理删除配送明细
		sql = "DELETE from delivery_details where delivery_id = :deliveryRecordId";
		jdbcTemplate.update(sql,map);

//		4.物理删除配送记录
		sql = "DELETE from delivery_records where id = :deliveryRecordId";
		jdbcTemplate.update(sql,map);


	}
}